package com.qfedu.dtboot.shiro;

import com.qfedu.dtboot.dao.SysUserDao;
import com.qfedu.dtboot.entity.SysUser;
import com.qfedu.dtboot.service.SysUserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Set;

/**
 * @ClassName UserRealm
 * @Author ykx
 * @Date 2022/9/28 11:28
 * @Version 1.0
 */
@Component
public class UserRealm extends AuthorizingRealm {

    @Autowired
    private SysUserService sysUserService;

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        System.out.println("认证");

        String usernameInput = (String) authenticationToken.getPrincipal();
        String passwordInput = new String ((char[]) authenticationToken.getCredentials());

        SysUser user = sysUserService.queryByUserName(usernameInput);
        if (user==null){
            throw new UnknownAccountException("账号或密码错误");
        }
        //数据库中获取的用户名和密码
        String username = user.getUsername();
        String password = user.getPassword();

        if (!passwordInput.equals(password)){
            throw new IncorrectCredentialsException("账号或密码错误");
        }
        if (!user.getStatus()){
            throw new LockedAccountException("账号被锁定，请联系管理员");
        }

        return new SimpleAuthenticationInfo(user, password, this.getName());
    }

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("授权");

        SysUser user = (SysUser)principalCollection.getPrimaryPrincipal();
        Set<String> userPermissions = sysUserService.getUserPermissions(user.getUserId());

        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        //info.addRoles(roleList);

        //资源授权
        List<String> permList = Arrays.asList("sys:menu:update");
        info.addStringPermissions(permList);

        return info;
    }
}
